package com.zbvc.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zbvc.dao.AdminDao;
import com.zbvc.dao.impl.AdminDaoImpl;
import com.zbvc.entity.Admin;

/**
 * 个人资料和密码修改
 */
@WebServlet(name = "updateAdmin", urlPatterns = { "/updateAdmin" })
public class UpdateAdminServlet extends HttpServlet {
	
	
	private AdminDao adminDao= new AdminDaoImpl();
	
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateAdminServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");		
		int tip = Integer.parseInt(request.getParameter("tip"));
		String url = request.getParameter("url");
		
		HttpSession session = request.getSession();
		Integer aid = (Integer)session.getAttribute("aid");
		PrintWriter out = response.getWriter();
		// tip等1修改密码，否则修改个人资料
		if(tip==1) {
			// 获取原密码和新密码
			String oldPwd = request.getParameter("password");
			String newPwd = request.getParameter("password2");
			// 如果原密码跟数据库一样，就修改，否则报”原密码不正确“
			Admin admin = adminDao.getAdminByAid(aid);
			
			if(admin.getPassword().equals(oldPwd)) {
				// 更新密码
				adminDao.updatePassword(aid, newPwd);
				response.sendRedirect("/book-manager/admin/"+url+".jsp");
				
			}else {
				out.print("<script>alert('原密码不正确'); location.href='"+url+".jsp';</script>");
			}
		}else { 
			//修改个人资料
			// 获取页面个人信息
			String name = request.getParameter("name");
			String email = request.getParameter("email");
			String phone = request.getParameter("phone");
			// 更新用户数据
			Admin admin = new Admin();
			admin.setAid(aid);
			admin.setEmail(email);
			admin.setPhone(phone);
			admin.setName(name);
			int row = adminDao.updateAdminByAid(admin);
			response.sendRedirect("/book-manager/admin/"+url+".jsp");
			
		}
	}

}
